﻿using System;
using System.Linq;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace Interscape.TwilioClient.ServiceHelpers
{
    /// <summary>
    /// A utility method to intercept incoming WCF messages and deserialize them into TwilioClient objects.
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public sealed class TwilioWcfSerializer : Attribute, IOperationBehavior, IClientMessageFormatter
    {
        #region Private Members

        private const string NullMessage = "TwilioResponse";
        IClientMessageFormatter _formatter;
        Type _return;
        
        #endregion

        #region IOperationBehavior Members

        public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
        {

        }

        public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
        {
            MessageDescription md = operationDescription.Messages.First(m => m.Direction == MessageDirection.Output);
            _return = md.Body.ReturnValue.Type;
            _formatter = clientOperation.Formatter;
            clientOperation.Formatter = this;
        }

        public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
        {

        }

        public void Validate(OperationDescription operationDescription)
        {

        }

        #endregion

        #region IClientMessageFormatter Members

        public object DeserializeReply(Message message, object[] parameters)
        {
            return ServiceUtility.DeserializeFromMessage(message, _return);
        }

        public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
        {
            return _formatter.SerializeRequest(messageVersion, parameters);
        }

        #endregion

    }
}



